package com.cjm.algorithm.leetcode;

import com.cjm.algorithm.TreeNode;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class IsSymmetric101 {

    public static boolean isSymmetric2(TreeNode root) {
        if (root == null) return true;
        Queue<TreeNode> queue = new LinkedBlockingQueue<>();
        queue.add(root.left);
        queue.add(root.right);
        while (!queue.isEmpty()) {
            TreeNode leftNode = queue.poll();
            TreeNode rightNode = queue.poll();

            if (leftNode == null && rightNode == null) {
                continue;
            }

            if (leftNode == null || rightNode == null || leftNode.val != rightNode.val) {
                return false;
            }

            queue.add(leftNode.left);
            queue.add(rightNode.right);
            queue.add(leftNode.right);
            queue.add(rightNode.left);
        }
        return true;
    }
    public static boolean isSymmetric1(TreeNode root) {
        return isMirror(root, root);
    }

    private static boolean isMirror(TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null) return false;
        return (left.val == right.val) && isMirror(left.left, right.right) && isMirror(left.right, right.left);
    }

    public static boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        Queue<Pair> queue =new LinkedList<>();
        queue.add(new Pair(root.left, root.right));
        while (!queue.isEmpty()) {
            Pair poll = queue.poll();
            TreeNode left = poll.left;
            TreeNode right = poll.right;
            if (left != null && right == null) {
                return false;
            }
            if (left == null && right != null) {
                return false;
            }
            if (left == null && right == null) continue;

            if (left.val != right.val) {
                return false;
            }
            queue.add(new Pair(left.left, right.right));
            queue.add(new Pair(left.right, right.left));
        }
        return true;
    }



    static class Pair {
        private TreeNode left;
        private TreeNode right;

        public Pair() {
        }

        public Pair(TreeNode left, TreeNode right) {
            this.left = left;
            this.right = right;
        }

        public TreeNode getLeft() {
            return left;
        }

        public void setLeft(TreeNode left) {
            this.left = left;
        }

        public TreeNode getRight() {
            return right;
        }

        public void setRight(TreeNode right) {
            this.right = right;
        }
    }

    public static void main(String[] args) {
        System.err.println(isSymmetric1(TreeNode.generatorTreeNode(new Integer[]{1,2,2,null,3,null,3})));
    }
}
